<template>
  <el-dialog :model-value="visibleRef" @update:model-value="onDialogVisibleChange" :title="editData ? '编辑催缴/沟通' : '新增催缴/沟通'">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="类型" prop="reminderType" required>
        <el-select v-model="form.reminderType" placeholder="请选择类型">
          <el-option
            v-for="item in REMINDER_TYPE_OPTIONS"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="内容" prop="reminderContent" required>
        <el-input v-model="form.reminderContent" type="textarea" :rows="4" placeholder="请输入催缴/沟通内容" />
      </el-form-item>
      <el-form-item label="记录时间" prop="reminderTime" required>
        <el-date-picker v-model="form.reminderTime" type="datetime" placeholder="请选择记录时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
      </el-form-item>
      <el-form-item label="下次到期日" prop="nextDueDate">
        <el-date-picker v-model="form.nextDueDate" type="date" placeholder="请选择下次到期日" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="下次应缴金额" prop="nextAmount">
        <el-input-number v-model="form.nextAmount" :min="0" :precision="2" :step="0.01" placeholder="请输入下次应缴金额" style="width: 100%" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息（可选）" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="submit" :loading="submitting">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits } from 'vue';
import { ElMessage } from 'element-plus';
import { REMINDER_TYPE_OPTIONS } from '../constants/enums';
import { reminderApi } from '@/api/property';

// 新增：类型定义，严格对齐后端
interface ReminderRecordForm {
  feeId: number | undefined;
  feeType: number | undefined;
  reminderType: number | undefined;
  reminderContent: string;
  reminderTime: string | undefined;
  nextDueDate?: string | undefined;
  nextAmount?: number | null | undefined;
  remark?: string | undefined;
}

const props = defineProps<{ visible: boolean; feeId: number; feeType: number; editData?: any }>();
const emit = defineEmits(['update:visible', 'refresh']);
const visibleRef = ref(props.visible);
const submitting = ref(false);

watch(() => props.visible, (val) => {
  visibleRef.value = val;
});

function onDialogVisibleChange(val: boolean) {
  emit('update:visible', val);
}

const formRef = ref();
// 表单初始值全部用null，类型安全
const form = ref<ReminderRecordForm>({
  feeId: props.feeId ?? undefined,
  feeType: props.feeType ?? undefined,
  reminderType: undefined,
  reminderContent: '',
  reminderTime: undefined,
  nextDueDate: undefined,
  nextAmount: null,
  remark: undefined
});
const rules = {
  feeId: [{ required: true, message: '费用主表ID不能为空', trigger: 'change' }],
  feeType: [{ required: true, message: '费用类型不能为空', trigger: 'change' }],
  reminderType: [{ required: true, message: '请选择类型', trigger: 'change' }],
  reminderContent: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 5, message: '内容至少5个字符', trigger: 'blur' }
  ],
  reminderTime: [{ required: true, message: '请选择记录时间', trigger: 'change' }],
  nextDueDate: [],
  nextAmount: [],
  remark: []
};

watch(() => props.visible, (val) => {
  if (val) {
    if (props.editData) {
      Object.assign(form.value, props.editData);
      if (form.value.nextAmount !== undefined && form.value.nextAmount !== null && form.value.nextAmount !== '') {
        form.value.nextAmount = Number(form.value.nextAmount)
      } else {
        form.value.nextAmount = null
      }
      // 新增：弹窗打开时打印 editData
      console.log('【ReminderRecordDialog】弹窗打开，props.editData:', props.editData);
      console.log('【ReminderRecordDialog】弹窗打开，form.value:', form.value);
    } else {
      Object.assign(form.value, {
        feeId: props.feeId ?? undefined,
        feeType: props.feeType ?? undefined,
        reminderType: undefined,
        reminderContent: '',
        reminderTime: undefined,
        nextDueDate: undefined,
        nextAmount: null,
        remark: undefined
      });
    }
  }
});

function close() {
  visibleRef.value = false;
  emit('update:visible', false);
}

async function submit() {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    submitting.value = true;
    // 类型安全：保证nextAmount为number或null
    if (form.value.nextAmount !== undefined && form.value.nextAmount !== null && form.value.nextAmount !== '') {
      form.value.nextAmount = Number(form.value.nextAmount)
    } else {
      form.value.nextAmount = null
    }
    // 构造提交参数，严格对齐后端字段，undefined字段不提交
    const submitData: any = {};
    if (form.value.feeId !== undefined) submitData.feeId = form.value.feeId;
    if (form.value.feeType !== undefined) submitData.feeType = form.value.feeType;
    if (form.value.reminderType !== undefined) submitData.reminderType = form.value.reminderType;
    if (form.value.reminderContent) submitData.reminderContent = form.value.reminderContent;
    if (form.value.reminderTime) submitData.reminderTime = form.value.reminderTime;
    if (form.value.nextDueDate) submitData.nextDueDate = form.value.nextDueDate;
    if (form.value.nextAmount !== null) submitData.nextAmount = form.value.nextAmount;
    if (form.value.remark) submitData.remark = form.value.remark;
    // 新增：编辑提交时打印 id
    if (props.editData && props.editData.id) {
      console.log('【ReminderRecordDialog】编辑提交，props.editData.id:', props.editData.id, 'submitData:', submitData);
      await reminderApi.updateReminderRecord(props.editData.id, submitData)
      ElMessage.success('催缴记录编辑成功')
    } else {
      await reminderApi.sendReminder(0, submitData)
      ElMessage.success('催缴记录创建成功')
    }
    emit('refresh');
    close();
  } catch (error: any) {
    console.error('提交催缴记录失败:', error);
    ElMessage.error(error.message || '操作失败，请重试');
  } finally {
    submitting.value = false;
  }
}
</script> 